<template>
    <el-dialog v-model="uploadOrderFileVisible" :show-close="false" width="50%">
        <!-- 自定义头部 -->
        <template #header="{ close, titleId, titleClass }">
            <div class="my-header">
                <h4 :id="titleId" :class="titleClass">上传订单文件 -- ESC关闭</h4>
                <el-button type="danger" @click="close">
                    <el-icon class="el-icon--left"><CircleCloseFilled /></el-icon>
                    关闭
                </el-button>
            </div>
        </template>
        <!-- 上传文件 -->
        <el-upload
            ref="uploadOrderFileRef"
            drag
            with-credentials
            accept=".jpeg,.jpg,.png,.webp,.pdf,.doc,.docx,.xls,.xlsx"
            :action="orderFileAction"
            :data="{
                customerName: props.customerName,
                fileName: props.fileName,
                orderId: props.orderId,
                newOrderFile: true,
                orderPassBack: orderPassBack,
                creator: useUserStore().username,
                creatorId: useUserStore().id,
            }"
            :limit="1"
            :auto-upload="false"
            :on-change="handleOrderFileChangeEvent"
            :on-exceed="handleOrderFileExceedEvent"
            :on-progress="uploadOrderFileProgressEvent"
            :on-success="uploadOrderFileSuccessEvent"
            :on-error="uploadOrderFileErrorEvent"
        >
            <el-icon class="el-icon--upload"><upload-filled /></el-icon>
            <div class="el-upload__text">拖拽文件到这里或者<em>点击上传</em></div>
            <template #tip>
                <div class="el-upload__tip">.jpg,.png,.webp,.dpf,.doc,.docx,.xls,.xlsx 文件大小不超过 20mb</div>
            </template>
        </el-upload>
        <!-- 提交按钮 -->
        <template #footer>
            <div class="w-full flex justify-between items-center">
                <el-checkbox v-model="orderPassBack" label="是否是回传" />
                <el-button type="primary" plain @click="orderFileSubmitEvent">上传</el-button>
            </div>
        </template>
    </el-dialog>
</template>

<script setup lang="ts">
import { HttpUrl } from '@/api/httpUrl';
import { bytesToMB } from '@/utils/calculate';
import { UploadFilled, CircleCloseFilled } from '@element-plus/icons-vue';
import { useUserStore } from '@store/modules/user';
import { genFileId, UploadFile, UploadFiles, UploadInstance, UploadProgressEvent, UploadProps, UploadRawFile } from 'element-plus';

/* ******************************通用属性/方法****************************** */
// model 声明
// 上传订单文件弹窗开关
const uploadOrderFileVisible = defineModel('uploadOrderFileVisible', { type: Boolean, default: false, required: true });
// props 声明
const props = defineProps<{
    orderId: string;
    customerName: string;
    fileName: string;
}>();

/* ******************************功能实现属性/方法****************************** */
// 订单文件上传地址
const orderFileAction = ref(
    import.meta.env.VITE_APP_UPLOAD_URL + import.meta.env.VITE_APP_BASE_API + HttpUrl.uploadOrderFile
);
// 上传的ref
const uploadOrderFileRef = ref<UploadInstance>();
// 订单回传的标识
const orderPassBack = ref(false);
// 订单文件发生变化时触发 文件类型验证  文件大小验证
const handleOrderFileChangeEvent = (uploadFile: UploadFile, _uploadFiles: UploadFiles) => {
    // 验证文件大小
    if (bytesToMB(uploadFile.size as number) > 20) {
        ElMessage({
            message: '文件大小不能超过20MB',
            type: 'warning',
            grouping: true,
        });
        uploadOrderFileRef.value!.clearFiles();
    }

    // 验证文件类型
    if (
        !(
            uploadFile.raw?.type == 'image/jpeg' ||
            uploadFile.raw?.type == 'image/jpg' ||
            uploadFile.raw?.type == 'image/png' ||
            uploadFile.raw?.type == 'image/webp' ||
            uploadFile.raw?.type == 'application/pdf' ||
            uploadFile.raw?.type == 'application/msword' ||
            uploadFile.raw?.type == 'application/vnd.openxmlformats-officedocument.wordprocessingml.document' ||
            uploadFile.raw?.type == 'application/vnd.ms-excel' ||
            uploadFile.raw?.type == 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
        )
    ) {
        ElMessage({
            message: '不支持的文件类型',
            type: 'warning',
            grouping: true,
        });
        uploadOrderFileRef.value!.clearFiles();
    }
};
// 再次拖拽/上传时覆盖前一个订单文件
const handleOrderFileExceedEvent: UploadProps['onExceed'] = (files) => {
    uploadOrderFileRef.value!.clearFiles();
    const file = files[0] as UploadRawFile;
    file.uid = genFileId();
    uploadOrderFileRef.value!.handleStart(file);
};
// 订单文件上传按钮点击事件
const orderFileSubmitEvent = () => {
    uploadOrderFileRef.value!.submit();
};
// 订单文件上传时的回调
const uploadOrderFileProgressEvent = (evt: UploadProgressEvent, _uploadFile: UploadFile, _uploadFiles: UploadFiles) => {
    console.log(evt);
};
// 订单文件成功上传的回调
const uploadOrderFileSuccessEvent = (response: any, _uploadFile: UploadFile, _uploadFiles: UploadFiles) => {
    ElMessage({
        message: response.message,
        type: 'success',
        grouping: true,
    });
    // 关闭弹窗
    uploadOrderFileVisible.value = false;
};
// 订单文件上传失败的回调
const uploadOrderFileErrorEvent = (_err: Error, _uploadFile: UploadFile, _uploadFiles: UploadFiles) => {
    ElMessage({
        message: '上传失败',
        type: 'error',
        grouping: true,
    });
};
</script>

<style scoped lang="scss">
.my-header {
    display: flex;
    flex-direction: row;
    justify-content: space-between;
    gap: 16px;
}
</style>
